<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi
 *
 */
class Hash extends AppModel {

	var $name = 'Hash';
	var $validate = array(
		'id' => array('notempty'),
		'url' => array('notempty'),
		'hash' => array('notempty')
	);

    
    function insertToHashTable($hashtype,&$dataarr) {
        
        foreach($dataarr as $arrval) {
            $hashstring = $this->get_rand_id(30);
             if ($hashtype == 'confirm') {
                $model = 'Attendance';
                $foreign_key = $arrval['Attendance']['id'];
                $url = "hash/$hashstring";
                $due_date = $arrval['Attendance']['confirm_duedate'];
                $due_date = str_replace("00:00:00", "23:59:59",  $due_date);
                $limit = 0;
                $limit_count = 0;
                
                $new = 0;
                $edit = 0;
                $k = $this->find('first',array('conditions'=>array('Model'=>'Attendance','foreign_key'=>$foreign_key)));
                
                if ($k) { // if already has hash record => edit
                    if ($k['Hash']['deleted'] == '1')  $edit = 1;
                    else $new = 1; 
                } else $new = 1; // add new hash record if not exist yet
                    
            }
			elseif($hashtype == 'password'){
                $model = 'User';
                $foreign_key = $arrval['User']['id'];
                $url = "hash1/$hashstring";
                $due_date = date('Y-m-d H:i:s',mktime(date('H'), date('i'), date('s'), date('m'), date('d')+Configure::read('days_to_remind'), date('Y')));
                $limit = 1;
                $limit_count = 0;
                $new = 0;
                $edit = 0;
                $k = $this->find('first',array('conditions'=>array('Model'=>'User','foreign_key'=>$foreign_key)));
                
                if ($k) { // if already has hash record => edit
                    if ($k['Hash']['deleted'] == '1')  $edit = 1;
                    else $new = 1; 
                } else $new = 1; // add new hash record if not exist yet
                    
            }
            
            if ($new) {
                $this->create();
                $data['model'] = $model;
                $data['foreign_key'] = $foreign_key;
                $data['url'] = $url;
                $data['hash'] = $hashstring;
                $data['hash_type'] = $hashtype;
                $data['limit'] = $limit;
                $data['limit_count'] = $limit_count;
                $data['due_date'] = $due_date;
                $this->save($data);
            } else if ($edit) { 
                $k['due_date'] = $due_date;
                $k['Hash']['deleted_date'] = '0000-00-00 00:00:00';
                $k['Hash']['deleted'] = '0';
                $this->save($k);
            }
        }
    }
    
    
    /**
     * Describe get_rand_id
     *
     * @param $length
     * @return random string with the length of $length
     */
    function get_rand_id($length) {
        $rand_id = "";
        if($length>0) {
            $char = array ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','x','y','z',
                    '1','2','3','4','5','6','7','8','9',
                    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','X','Y','Z'
                    );
            for($i=1; $i<=$length; $i++) {
                $rand_id .= $char[mt_rand(0,count($char)-1)];
            }
            if (!count($this->findByHash($rand_id))) $this->get_rand_id($length); //if hash not unique, regenerate it 
            else return $rand_id;
        } else {
            return false;
        }
    }
    
    function removeData($hashtype,$foreign_key) {
        if ($hashtype == 'confirm') {
            //$t = $this->find('first',array('conditions'=>array('model'=>'Attendance','foreign_key'=>$foreign_key,'deleted'=>array(0,1))));
            $t = $this->find('first',array('conditions'=>array('model'=>'Attendance','foreign_key'=>$foreign_key)));
            if ($t) {
                $t['Hash']['deleted'] = 1;
                $t['Hash']['deleted_date'] = date('Y-m-d H:i:s');
                $this->save($t);
            }
        }
    }
    
    function newPassword(){
        return $this->get_rand_id(6);
    }
    
    function updateHash($old,$new){
        $o_user=array_filter(Set::extract($old,'{n}.Attendance.user_id'));
        $n_user=array_filter(Set::extract($new,'{n}.Attendance.user_id'));
        $invited=array_diff($n_user,$o_user);
        $toInsert=array();
        foreach($invited as $i=>$invited){
            $toInsert[]=$new[$i];
        }
        if(!empty($toInsert)){
            $this->insertToHashTable('confirm',$toInsert);
        }
        $edit_n=array_flip(array_intersect($n_user,$o_user));
        $edit_o=array_flip(array_intersect($o_user,$n_user));
        foreach($edit_o as $key=>$o){
            $hash=$this->find('first',array('conditions'=>array('Hash.foreign_key'=>$old[$o]['Attendance']['id'],'hash_type'=>'confirm'),'order'=>'updated DESC'));
            $hash['Hash']['due_date']=$new[$edit_n[$key]]['Attendance']['confirm_duedate'];
            $hash['Hash']['foreign_key']=$new[$edit_n[$key]]['Attendance']['id'];
            $this->save($hash);
        }
    }
    
    function due_date($oridate){
        list($date,$time) = explode(' ', $oridate);
        $date = explode('-', $date);
        $time = explode(':',$time);
        $days=(Configure::read('days_to_confirm_attendance')>0)?Configure::read('days_to_confirm_attendance'):'0';
        return date('Y-m-d H:i:s',mktime(0,0,0, $date[1], intval($date[2])-$days, $date[0]));
    }
}
?>
